package com.example.service;

import com.example.entity.College;
import com.example.entity.Major;
import com.example.exception.CustomException;
import com.example.mapper.ClazzMapper;
import com.example.mapper.MajorMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MajorService {
    @Resource
    private MajorMapper majorMapper;
    @Resource
    private ClazzMapper clazzMapper;

    public List<Major> selectAll(Major major) {
        return majorMapper.selectAll(major);
    }
    public PageInfo<Major> selectPage(Major major, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Major> list = majorMapper.selectAll(major);
        return PageInfo.of(list);
    }

    public void add(Major major) {
        if (majorMapper.countByMajorName(major.getMajorName()) > 0) {
            throw new CustomException("400","学院已存在");
        }
        majorMapper.insert(major);
    }

    public void update(Major major) {
        Major exstingMajor = majorMapper.selectById(major.getMajorId());
        if (exstingMajor.getMajorName().equals(major.getMajorName())){
            if (exstingMajor.getCollegeId().equals(major.getCollegeId())){
                return;
            }
        } else {
            if (majorMapper.countByMajorName(major.getMajorName()) > 0) {
                throw new CustomException("400","学院已存在");
            }
        }
        majorMapper.update(major);
    }

    public void delete(Integer majorId) {
        if (clazzMapper.countByMajorId(majorId) > 0){
            throw new CustomException("400","存在关联班级");
        }
        majorMapper.delete(majorId);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer majorId : ids) {
            if (clazzMapper.countByMajorId(majorId) > 0){
                throw new CustomException("400","选中专业中存在关联班级");
            }
        }
        for (Integer majorId : ids) {
            majorMapper.delete(majorId);
        }
    }

}
